package com.rongxing.config;

import com.github.pagehelper.PageInterceptor;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.datasource.DataSourceDecipher;
import com.mybatisflex.core.datasource.DataSourceProperty;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement(proxyTargetClass = true)
@AutoConfiguration
@MapperScan("com.rongxing.**.mapper")
public class MybatisFlexConfig {

    private static final Logger logger = LoggerFactory.getLogger("mybatis-flex-sql");

    public MybatisFlexConfig() {
        //开启审计功能
        AuditManager.setAuditEnable(true);

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage ->
                logger.info("{},{}ms", auditMessage.getFullSql(), auditMessage.getElapsedTime())
        );
    }

    /**
     * 数据源解密
     * @return
     */
    @Bean
    public DataSourceDecipher decipher(){
        DataSourceDecipher decipher = new DataSourceDecipher() {
            @Override
            public String decrypt(DataSourceProperty property, String value) {
                //解密用户名，通过编码支持任意加密方式的解密
                if (property == DataSourceProperty.USERNAME) {
                    return value.substring(0, 8);
                }
                //解密密码
                else if (property == DataSourceProperty.PASSWORD) {
                    return value.substring(0, 6);
                }
                return value;
            }
        };
        return decipher;
    }

    /**
     * pagehelper分页插件
     * @return
     */
    @Bean
    public PageInterceptor pageInterceptor(){
        //var i = new PageInterceptor();
        //转小驼峰用
        var i = new MyPageInterceptor();
        /*Properties properties = new Properties();
        properties.put("dialetAlias","lealone=com.github.pagehelper.dialect.helper.PostgreSqlDialect");
        i.setProperties(properties);*/
        return i;
    }
}
